#ifndef LINKLIST_H
#define LINKLIST_H

#include<stdio.h>
#include<stdlib.h>

#ifndef DATATYPE
#define DATATYPE int
#endif

typedef DATATYPE datatype;//链表数据类型

typedef struct node
{
    datatype data;
    struct node *prev;
    struct node *next;
}dlistnode, *dlinklist;

//API
//初始化链表
static dlinklist init_list(void){
    dlinklist head = (dlinklist)malloc(sizeof(dlistnode));
    if(head != NULL){
        head->prev = head;
        head->next = head;
    }
    return head;
}

//新建节点
static dlinklist new_node(datatype data, void (*assign)(datatype*, const datatype*)){
    dlinklist new_node = (dlinklist)malloc(sizeof(dlistnode));
    if(new_node != NULL){
        if(assign != NULL)
            assign(&new_node->data, &data);
        else
            new_node->data = data;
        new_node->prev = new_node;
        new_node->next = new_node;
    }
    return new_node;
}

//新建节点
static dlinklist my_new_node(datatype data){
    dlinklist new_node = (dlinklist)malloc(sizeof(dlistnode));
    if(new_node != NULL){
        new_node->data = data;
        new_node->prev = new_node;
        new_node->next = new_node;
    }
    return new_node;
}

//尾插法插入节点
static void list_add_tail(dlinklist head, dlinklist new_node){
    new_node->prev = head->prev;
    new_node->next = head;

    head->prev->next = new_node;
    head->prev = new_node;
}

//遍历链表
static void list_for_each(dlinklist head, void (*callback)(datatype)){
    dlinklist p = head->next;
    while(p != head){
        callback(p->data);
        p = p->next;
    }
}

#endif